package com.crois.barrier.web.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.PriorityOrdered;
import org.springframework.core.env.ConfigurableEnvironment;

import java.util.Arrays;

import static com.crois.barrier.common.constants.Constants.STANDALONE_MODE_PROPERTY_NAME;
import static com.crois.barrier.common.constants.Constants.STANDALONE_SPRING_PROFILE;
import static com.crois.barrier.common.utils.SystemUtils.STANDALONE_MODE;

/**
 * @author Hou Ze Yu
 * @description
 * @date 2020/10/12
 */
public class StandaloneProfileApplicationListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent>,
        PriorityOrdered {

    private static final Logger logger = LoggerFactory.getLogger(StandaloneProfileApplicationListener.class);

    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {

        ConfigurableEnvironment environment = event.getEnvironment();

        if (environment.getProperty(STANDALONE_MODE_PROPERTY_NAME, boolean.class, false)) {
            environment.addActiveProfile(STANDALONE_SPRING_PROFILE);
        }
        if (logger.isInfoEnabled()) {
            logger.info("Spring Environment's active profiles : {} in standalone mode : {}",
                    Arrays.asList(environment.getActiveProfiles()),
                    STANDALONE_MODE
            );
        }

    }

    @Override
    public int getOrder() {
        return HIGHEST_PRECEDENCE;
    }
}
